import os
import requests
from django.core.management.base import BaseCommand
from django.conf import settings

class Command(BaseCommand):
    help = '下载 htmx.min.js 文件到静态目录'

    def handle(self, *args, **options):
        # htmx CDN URL
        htmx_url = 'https://unpkg.com/htmx.org/dist/htmx.min.js'
        
        # 确定存放目录
        static_dir = os.path.join(settings.BASE_DIR, 'static', 'js')
        if not os.path.exists(static_dir):
            os.makedirs(static_dir)
            
        # 下载文件路径
        file_path = os.path.join(static_dir, 'htmx.min.js')
        
        try:
            # 下载文件
            response = requests.get(htmx_url)
            response.raise_for_status()
            
            # 保存文件
            with open(file_path, 'wb') as f:
                f.write(response.content)
                
            self.stdout.write(self.style.SUCCESS(f'成功下载 htmx.min.js 到 {file_path}'))
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'下载失败: {str(e)}')) 